<template>
    <el-container>
        <el-aside style="width:380px;">
            <div style="margin-top:20px;margin-left:25px;">
                <el-card style="width:320px;">
                    <div slot="header">
                        <div style="text-align:left;">分析结果</div>
                        <el-tooltip placement="right" effect="light">
                            <div slot="content">
                                <div style="font-size:13px;margin-left:8px;margin-bottom:8px;color:#303133">分析结果说明<br/></div>
                                <el-tag type="warning" small style="margin-left:8px;margin-right:4px;margin-bottom:8px;">黄色</el-tag>表示阳性, 说明患者有该症状/检查<br/>
                                <el-tag type="success" small style="margin-left:8px;margin-right:4px;margin-bottom:8px;">绿色</el-tag>表示阴性, 说明患者没有该症状/检查<br/>
                                <el-tag type="info" small style="margin-left:8px;margin-right:4px;margin-bottom:8px;">灰色</el-tag>表示未知, 表示当前对话未明确患者是否有该症状<br/>
                                <el-badge value="D" type="primary"><el-tag small style="margin-left:8px;margin-right:4px;margin-bottom:8px;">示例</el-tag></el-badge>(右上角含有D标记)表示该信息为医生诊断<br/>
                            </div>
                            <el-button type="info" icon="el-icon-info" style="margin-top:-19px;float:right;padding:0;border:0" circle></el-button>
                        </el-tooltip>
                    </div>
                    <div>
                        <el-row v-for="(pred, index) in pred_info" :key="index" style="margin-bottom:5px;">
                            <el-col :span="4" style="margin-top:6px;font-size:14px;">{{ pred.category }}:</el-col>
                            <el-col type="flex" justify="space-around" :span="9" v-for="(item, i) in pred.item" :key="i">
                                <el-badge value="D" :type="item.color" :hidden="item.hasDot" >
                                    <el-button @click="checkSymptom(pred.category, item.name)" style="width:100px;font-size:12px;padding:10px 0px 10px 0px;margin-bottom:10px;" :type="item.color" :icon="item.icon" round plain>{{item.name}}</el-button>
                                </el-badge>
                            </el-col>
                        </el-row>
                    </div>
                    <div>
                        <el-divider></el-divider>
                        <el-row style="margin-bottom:6px;font-size:14px;">
                            <el-col :span="4"><el-tag effect="plain">姓名</el-tag></el-col>
                            <el-col :span="8" style="margin-top:6px;"> {{ patient_info.name }}</el-col>
                        </el-row>
                        <el-row style="margin-bottom:6px;font-size:14px;">
                            <el-col :span="4"><el-tag effect="plain">性别</el-tag></el-col>
                            <el-col :span="8" style="margin-top:6px;">{{ patient_info.gender }}</el-col>
                        </el-row>
                        <el-row style="margin-bottom:6px;font-size:14px;">
                            <el-col :span="4"><el-tag effect="plain">生日</el-tag></el-col>
                            <el-col :span="8" style="margin-top:6px;">{{ patient_info.birth }}</el-col>
                        </el-row>
                        <el-row style="margin-bottom:6px;font-size:14px;">
                            <el-col :span="4"><el-tag effect="plain">问诊</el-tag></el-col>
                            <el-col :span="8" style="margin-top:6px;">{{ patient_info.dialogue }}</el-col>
                        </el-row>
                    </div>
                </el-card>
            </div>
             <el-card style="width:320px;margin-top:20px;margin-bottom:20px;margin-left:25px;">
                <div id="myChart" style="width:300px;height:300px;margin-left:-10px;"></div>
            </el-card>
        
        </el-aside>

        <el-main class="main" v-loading="loadStatus">
            <el-row>
                <el-col :span="12"><div id="pieChart" style="width:500px;height:500px;"></div></el-col>
                <el-col :span="12">
                    <el-row style="margin-top:40px;margin-left:85px">
                        <el-button @click="pieChange('症状')" round>症状</el-button>
                        <el-button @click="pieChange('一般信息')" round>一般信息</el-button>
                        <el-button @click="pieChange('检查')" round>检查</el-button>
                    </el-row>
                    <el-row>
                        <el-card shadow="hover" style="width:300px;height:380px;margin-left:100px;margin-top:15px;">
                            <div style="font-size:20px;color:#303133;margin-top:10px;margin-left:20px;text-align:left;">{{ cur_item }}</div>
                            <div style="font-size:14px;color:#303133;margin-top:10px;margin-left:20px;margin-right:20px;text-align:left;">
                                根据PatientGraph图谱, 在有相同症状的患者中, 对话中提到了以下{{ cur_status }}:
                            </div>
                            <div>
                                <el-table
                                :data="list"
                                style="width: 320px;font-size:13px;"
                                stripe
                                max-height="210px"
                                >
                                <el-table-column
                                    prop="name"
                                    label="item"
                                    width="100px;"
                                    align="center"
                                    header-align="center">
                                </el-table-column>
                                <el-table-column
                                    prop="positive"
                                    label="阳性"
                                    width="50px;"
                                    align="center"
                                    header-align="center">
                                </el-table-column>
                                <el-table-column
                                    prop="negative"
                                    label="阴性"
                                    align="center"
                                    header-align="center"
                                    width="50px;">
                                </el-table-column>
                                <el-table-column
                                    prop="unknown"
                                    label="未知"
                                    width="50px;"
                                    align="center"
                                    header-align="center">
                                </el-table-column>
                                </el-table>
                            </div>
                        </el-card>
                    </el-row>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <div id="piePosChart" style="width:500px;height:500px;"></div>
                    <div style="margin-left:100px;margin-bottom:40px;">
                    <el-switch
                        style="display: block"
                        v-model="cur_pos"
                        active-color="#FFA1D2"
                        inactive-color="#A9FFFD"
                        active-text="确诊比例"
                        inactive-text="确诊数量"
                        active-value = "确诊比例"
                        inactive-value = "确诊数量"
                        @change="changePiePos()">
                    </el-switch>
                    </div>
                </el-col>
                <el-col :span="12">
                    <el-card shadow="hover" style="width:300px;height:170px;margin-left:100px;margin-top:50px;">
                        <div style="font-size:20px;color:#303133;margin-top:0px;margin-left:20px;text-align:left;">确诊数量</div>
                        <div style="font-size:14px;color:#303133;margin-top:10px;margin-left:20px;margin-right:20px;text-align:left;">
                            查找对话中提到{{ cur_status }}【{{ cur_item }}】的病人, 并查看这些病人具有的其他症状, 
                            将这些症状中诊断为【阳性】的案例绘制成【确诊数量】饼图.
                        </div>
                    </el-card>
                    <el-card shadow="hover" style="width:300px;height:180px;margin-left:100px;margin-top:15px;">
                        <div style="font-size:20px;color:#303133;margin-top:0px;margin-left:20px;text-align:left;">确诊比例</div>
                        <div style="font-size:14px;color:#303133;margin-top:10px;margin-left:20px;margin-right:20px;text-align:left;">
                            【确诊数量】展现的是症状数量的饼图, 而【确诊比例】展示的是该症状中确诊的比例(比例=阳性/(阳性+阴性+未知)). 
                            如果某个症状总共只有1例, 则不计入本饼图.
                        </div>
                    </el-card>
                    <el-button style="margin-top:20px;margin-left:100px;" round>上传患者信息</el-button>
                </el-col>
            </el-row>
        </el-main>
        
    </el-container>    
</template>

<script>
import axios from 'axios'
import echarts from 'echarts'
export default {
    name:"upload",
    data() {
        return {
            name: "上传文件",
            checkStatus: "",
            activeTab: 'first',
            loadingbut:false,
            loadingbutText:"点击查看",
            btnIcon:" ",
            graph_data: undefined,
            myChart: null,
            chartWidth: 300+'px',
            chartHeight: 300+'px',
            pieChart: null,
            loadStatus: false,
            data:[],
            links:[],
            entities:[],
            relations:[],
            patient_info: {},
            pred_info: [],
            pie_info: [],
            // patient_info : {'name': 'Maddy', 'gender': 'female', 'birth': '1999.6.2', 'dialogue': '2020.4.18'},
            // pred_info:  [{'category': '症状', 'item': [{'name': '心律不齐', 'color': 'warning', 'icon': 'el-icon-check', 'hasDot': 'false'}]}, 
            //             {'category': '检查', 'item': [{'name': '体检', 'color': 'warning', 'icon': 'el-icon-check', 'hasDot': 'true'}, {'name': '心电图', 'color': 'warning','icon': 'el-icon-check', 'hasDot': 'false'}]}],
            // pie_info: {"一般信息":[{'content': [{'value': 9, 'name': '饮食'}, {'value': 12, 'name': '睡眠'}, {'value': 9, 'name': '精神状态'}]},
            //                         {'饮食': [1, 2, 0], '睡眠': [2, 7, 0],'精神状态':[7,2,0]},{'max': 12}],
            //             "症状":[{'content': [{'value': 3, 'name': '饮食'}, {'value': 4, 'name': '睡眠'}, {'value': 5, 'name': '精神状态'}]},
            //                         {'饮食': [1, 2, 0], '睡眠': [2, 7, 0],'精神状态':[7,2,0]}, {'max': 5}]},
            cur_status: "症状",
            pie_color:{"症状":"#6A9CFF", "一般信息": "#66C6A3", "检查": "#C9E275"},
            cur_item: "测试文字",
            table_title:[
                {
                    positive: 'positive',
                    negative: 'negative',
                    unknown: 'unknown',
                    width: '100',
                    titleAlign: 'center',
                    columnAlign: 'center',

                },
            ],
            list:[],
            piePosChart: null,
            pie_pos: [],
            pie_pos_percent: [],
            max_pos:0,
            max_percent:0,
            cur_pos:"确诊数量",
            pos_color:{"确诊数量": "#00FFFF", "确诊比例": "#E867B1"},
        }
    },
    created() {
        this.getRouterData()
    },
    methods: {
        getRouterData(){
            this.data = this.$route.params.data;
            this.links = this.$route.params.links;
            this.entities = this.$route.params.entities;
            this.relations = this.$route.params.relations;
            this.patient_info = this.$route.params.patient_info;
            var genders = {"male": "男", "female": "女"};
            this.patient_info.gender = genders[this.patient_info.gender];
            console.log(this.patient_info)
            this.pred_info = this.$route.params.pred_info;
            this.pie_info = this.$route.params.pie_info;
            this.cur_item = this.$route.params.item;
            for(var i=0;i < this.pred_info.length;i++){
                for(var j=0;j < this.pred_info[i]["item"].length;j++){
                    if(this.pred_info[i]["item"][j]["hasDot"] == "false"){
                        this.pred_info[i]["item"][j]["hasDot"] = false;
                    }else{
                        this.pred_info[i]["item"][j]["hasDot"] = true;
                    }
                }
            }
            console.log("pred_info:",this.pred_info)
            this.list = this.getList("症状");
            this.getPiePos("症状");
        },
        getList(cur_status){
            var list = [];
            var pie_data = this.pie_info[cur_status][0]["content"].sort(function (a, b) {return b.value - a.value;});
            var info = this.pie_info[cur_status][1];
            for(var i = 0; i<pie_data.length; i++){
                var name = pie_data[i]['name']
                list.push({'name':name, 'positive':info[name][0], 'negative':info[name][1], 'unknown':info[name][2]})
            }
            return list
        },
        getPiePos(cur_status){
            var pie_pos = [];
            var pie_percent = [];
            var max_pos = 0;
            var max_percent = 0;
            var info = this.pie_info[cur_status][1];
            console.log("info", info);
            for(var key in info){
                var pos_num = info[key][0];
                if(pos_num == 0){
                    continue;
                }
                var pos_percent = info[key][0]/(info[key][0]+info[key][1]+info[key][2]);
                pos_percent = (Math.round(pos_percent *1000))/1000 * 100;
                if(pos_num > max_pos){
                    max_pos = pos_num;
                };
                if(pos_percent > max_percent){
                    max_percent = pos_percent;
                };
                pie_pos.push({value: pos_num, name: key})
                if(pos_num == 1){
                    continue;
                }
                pie_percent.push({value: pos_percent, name: key})
            }
            this.pie_pos = pie_pos;
            this.pie_percent = pie_percent;
            this.max_pos = max_pos;
            this.max_percent = max_percent;
        },
        test(){
            var info = {"category":"Symptom", "item": "心律不齐"};
            axios.post("http://localhost:8000/dialogue/record_analysis/",JSON.stringify(info),{
                headers: {
                    'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(res => {
                console.log(res)
                this.pie_info = res.data;
            });
        },
        show(){
            let echarts = require('echarts/lib/echarts');
            this.myChart = echarts.init(document.getElementById('myChart'));
            console.log(document.getElementById('myChart'));
            var categories = [];

            for (var i = 0; i < this.entities.length; i++) {

                categories[i] = {name: this.entities[i]};
            }


            let option = {
                // title: {text: '抽取结果图谱展示'},

                tooltip: {
                    formatter: function (x) {
                    return x.data.des;
                    }
                },

                toolbox: {
                    show: true,
                    feature: {
                        mark: {
                        show: true
                        },
                        restore: {
                        show: true
                        },
                        saveAsImage: {
                        show: true
                        }
                    }
                },
                legend: [{
                    data: categories.map(function (a) {
                    return a.name;
                    })
                }],

                series: [{
                    type: 'graph', // 类型:关系图
                    layout: 'force', //图的布局，类型为力导图
                    symbolSize: 40, // 调整节点的大小
                    roam: true, // 是否开启鼠标缩放和平移漫游。默认不开启。如果只想要开启缩放或者平移,可以设置成 'scale' 或者 'move'。设置成 true 为都开启
                    edgeSymbol: ['circle', 'arrow'],
                    edgeSymbolSize: [2, 10],
                    edgeLabel: {
                        normal: {
                            textStyle: {
                            fontSize: 20
                            }
                        }
                    },
                    force: {
                    repulsion: 2500,
                    edgeLength: [10, 50]
                    },
                    draggable: true,
                    lineStyle: {
                        normal: {
                        width: 2,
                        color: '#4b565b',
                        }
                    },
                    edgeLabel: {
                        normal: {
                        show: true,
                        formatter: function (x) {
                            return x.data.name;
                        }
                        }
                    },
                    label: {
                        normal: {
                        show: true,
                        textStyle: {}
                        }
                    },
                    data: this.data,
                    links: this.links,
                    categories: categories,

                    // data: [{'name':'肺泡蛋白质沉积症','symbolSize':80,'category':'Disease'},{'name':'呼吸内科','symbolSize':70,'category':'Category'}],
                    // links:[{'target':'呼吸内科','source':'肺泡蛋白质沉积症','name':'category','des':'属于'}],
                    // categories: [{'name':'Disease'},{'name':'Category'}],
                }]
            };
            this.myChart.setOption(option);
        },
        showPieChart(){
            let piecharts = require('echarts/lib/echarts');
            this.pieChart = piecharts.init(document.getElementById('pieChart'));
            var option;
            var pie_data = this.pie_info[this.cur_status][0]["content"];
            var tooltip_data = this.pie_info[this.cur_status][1];
            var max = this.pie_info[this.cur_status][2]['max'];
            var text = this.cur_status;
            var color = this.pie_color[this.cur_status];
            option = {
            backgroundColor: '#f3f3f4',
            title: {
                text: text,
                left: 'center',
                top: 20,
                textStyle: {
                color: '#ccc'
                }
            },
            tooltip: {
                trigger: 'item'
            },
            visualMap: {
                show: false,
                min: 0,
                max: max,
                inRange: {
                colorLightness: [0.2, 0.9]
                }
            },
            series: [
                {
                name: 'Access From',
                type: 'pie',
                radius: '55%',
                center: ['50%', '50%'],
                data: pie_data.sort(function (a, b) {
                    return a.value - b.value;
                }),
                roseType: 'radius',
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        console.log(params)                       
                        var name = params.name;

                        var res = "<div><span>" + name
                        + "</span></div><div style='width:100px;font-size: 14px;'><table style='width:100%;'>";

                        res += "<tr><td style='color:#E6A23C'>阳性</td><td>"+tooltip_data[name][0]+"</td></tr>";
                        res += "<tr><td style='color:#67C23A'>阴性</td><td>"+tooltip_data[name][1]+"</td></tr>";
                        res += "<tr><td style='color:#909399'>未知</td><td>"+tooltip_data[name][2]+"</td></tr>";
                        
                        res += "</table></div>";
                        return res;
                    }
                },
                label: {
                    color: '#606266'
                },
                labelLine: {
                    lineStyle: {
                    color: '#606266'
                    },
                    smooth: 0.2,
                    length: 10,
                    length2: 20
                },
                itemStyle: {
                    color: color,
                    shadowBlur: 100,
                    shadowColor: 'rgba(0, 0, 0, 0.2)'
                },
                animationType: 'scale',
                animationEasing: 'elasticOut',
                animationDelay: function (idx) {
                    return Math.random() * 200;
                }
                }
            ]
            };

            this.pieChart.setOption(option);
        },
        pieChange(category){
            this.cur_status = category;
            this.list = this.getList(this.cur_status);
            this.pieRefresh();
            this.getPiePos(this.cur_status);
            this.piePosRefresh();
        },
        changePiePos(){
            console.log(this.cur_pos);
            this.getPiePos(this.cur_status);
            this.piePosRefresh();
        },
        checkSymptom(category, item){
            this.loadStatus = true;
            if(category == "症状"){
                var info = {"category": "Symptom", "item": item};
                axios.post("http://localhost:8000/dialogue/record_analysis/",JSON.stringify(info),{
                    headers: {
                        'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
                    }
                }).then(res => {
                    this.pie_info = res.data;
                    this.cur_status = "症状";
                    this.cur_pos = "确诊数量";
                    this.cur_item = item;
                    this.list = this.getList("症状");
                    this.pieRefresh();
                    this.getPiePos("症状");
                    this.piePosRefresh();
                    this.loadStatus = false;
                });
            }
        },
        pieRefresh(){
            // 改变颜色、信息
            var pie_data = this.pie_info[this.cur_status][0]["content"];
            var tooltip_data = this.pie_info[this.cur_status][1];
            var max = this.pie_info[this.cur_status][2]['max'];
            var color = this.pie_color[this.cur_status];
            var text = this.cur_status;
            var option = this.piePosChart.getOption();
            option.title = {
                                text: text,
                                left: 'center',
                                top: 20,
                                textStyle: {
                                color: '#ccc'
                                }
                            };
            option.series[0].data = pie_data.sort(function (a, b) {return a.value - b.value;});
            option.series[0].tooltip = {
                                            trigger: 'item',
                                            formatter: function (params) {
                                                // console.log(params)                       
                                                var name = params.name;

                                                var res = "<div><span>" + name
                                                + "</span></div><div style='width:100px;font-size: 14px;'><table style='width:100%;'>";

                                                res += "<tr><td style='color:#E6A23C'>阳性</td><td>"+tooltip_data[name][0]+"</td></tr>";
                                                res += "<tr><td style='color:#67C23A'>阴性</td><td>"+tooltip_data[name][1]+"</td></tr>";
                                                res += "<tr><td style='color:#909399'>未知</td><td>"+tooltip_data[name][2]+"</td></tr>";
                                                
                                                res += "</table></div>";
                                                return res;
                                            }
                                        };
            option.series[0].itemStyle = {
                                            color: color,
                                            shadowBlur: 100,
                                            shadowColor: 'rgba(0, 0, 0, 0.2)'
                                        };
            option.visualMap = {
                                show: false,
                                min: 0,
                                max: max,
                                inRange: {
                                colorLightness: [0.2, 0.9]
                                }
                            };
            this.pieChart.setOption(option);
        },
        showPiePos(){
            let piecharts = require('echarts/lib/echarts');
            this.piePosChart = piecharts.init(document.getElementById('piePosChart'));
            var option;
            var pie_data = this.pie_pos;
            var max = this.max_pos;
            var text = this.cur_pos;
            var name = "阳性" + this.cur_pos.substring(2);
            var color = this.pos_color[this.cur_pos];
            option = {
            backgroundColor: '#f3f3f4',
            title: {
                text: text,
                left: 'center',
                top: 20,
                textStyle: {
                color: '#ccc'
                }
            },
            tooltip: {
                trigger: 'item'
            },
            visualMap: {
                show: false,
                min: 0,
                max: max,
                inRange: {
                colorLightness: [0, 0.9]
                }
            },
            series: [
                {
                name: name,
                type: 'pie',
                radius: '55%',
                center: ['50%', '50%'],
                data: pie_data.sort(function (a, b) {
                    return a.value - b.value;
                }),
                roseType: 'radius',
                label: {
                    color: '#606266'
                },
                labelLine: {
                    lineStyle: {
                    color: '#606266'
                    },
                    smooth: 0.2,
                    length: 10,
                    length2: 20
                },
                itemStyle: {
                    color: color,
                    shadowBlur: 100,
                    shadowColor: 'rgba(0, 0, 0, 0.2)'
                },
                animationType: 'scale',
                animationEasing: 'elasticOut',
                animationDelay: function (idx) {
                    return Math.random() * 200;
                }
                }
            ]
            };

            this.piePosChart.setOption(option);
        },
        piePosRefresh(){
            // 改变颜色、信息
            if(this.cur_pos=="确诊数量"){
                var pie_data = this.pie_pos;
                var max = this.max_pos;
            }else{
                var pie_data = this.pie_percent;
                var max = this.max_percent;
            }
            var color = this.pos_color[this.cur_pos];
            var text = this.cur_pos;
            var name = "阳性" + this.cur_pos.substring(2);
            var option = this.piePosChart.getOption();
            option.title = {
                                text: text,
                                left: 'center',
                                top: 20,
                                textStyle: {
                                color: '#ccc'
                                }
                            };
            option.series[0].name = name;                
            option.series[0].data = pie_data.sort(function (a, b) {return a.value - b.value;});
            option.series[0].itemStyle = {
                                            color: color,
                                            shadowBlur: 100,
                                            shadowColor: 'rgba(0, 0, 0, 0.2)'
                                        };
            option.visualMap = {
                                show: false,
                                min: 0,
                                max: max,
                                inRange: {
                                colorLightness: [0, 0.9]
                                }
                            };
            this.piePosChart.setOption(option);
        },
        getDate(){
            var now = new Date();
            var year = now.getFullYear();    
            var month = now.getMonth() + 1;  
            var day = now.getDate();  
            var date = year.toString() + "." + month.toString() + "." + day.toString();   
            return date
        },
        goToNext(){
            this.loadingbut = true;
            this.loadingbutText = "生成中...";
            this.btnIcon = "el-icon-loading";
            console.log(this.loadingbut);
            var name = this.$store.state.current_graph_name;
            var date = this.getDate();
            var info = {"name":name, "date": date, "type":"结构化文件","entities":this.entities, "relations":this.relations}
            console.log(info);
            axios.post("http://localhost:8000/polls/save_graph/",JSON.stringify(info),{
                headers: {
                    'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(res => {
                console.log(res);
                axios.get("http://localhost:8000/after_creation/").then(res=>{
                    var data = res.data.data;
                    var links = res.data.links;
                    var entities = res.data.entities;
                    var relations = res.data.relations;
                    this.$router.push({  
                        name:'Kgshow_Disease',
                        params:{
                            data:data,
                            links:links,
                            entities:entities,
                            relations:relations,
                        }
                    })
                    this.loadingbut = false;
                    this.loadingbuttext = "点击查看";
                    this.$message({
                        message: '图谱保存成功!',
                        type: 'success'
                    });
                })
            });
        }
        
    },
    mounted: function(){
	    this.show();//需要触发的函数
        this.showPieChart();
        this.showPiePos();
    }
}
</script>
<style scoped>
    .el-aside{
        background-color: #ffffff;
    }
    
    .main{
        background-color: #f3f3f4;
    }
    .main-container{
        position:absolute;
        height:100%;
        width:100%;
    }
    .card-box{
        margin-top:100px;
    }
    .tab-title{
        color:#fff;
    }

</style>